import React, { useEffect, useRef, useState } from 'react'
import {
    removeUnusedOnlinePicture,
    removeUnusedPicture,
    // requestAddShopList,
    requestModifyShopList
} from '../../api/shop'
import { requestAddBrandList, requestBrandlist } from '../../api/brand'
import { requestAddCategoryList, requestCategoryList } from '../../api/category'
import { Button, Divider, Form, Input, InputNumber, message, Modal, Select, Space, Typography, Upload } from 'antd'
import { PlusOutlined, UploadOutlined } from '@ant-design/icons'
import { baseUrl } from '../../project.config'
import { connect } from 'react-redux'
// import QueueAnim from 'rc-queue-anim'

const { Option } = Select

const normFile = (e) => {
    if (Array.isArray(e)) {
        return e
    }
    return e && e.fileList
}
// edit:boolean initData:Form  proid:id cb:Function
export const AddShop = (props) => {
    const fromRef = useRef()
    const [previewVisible, setPreviewVisible] = useState(false)
    const [previewImg, setPreviewImg] = useState({ filename: '', path: '' })
    const [categorys, setCategorys] = useState([])
    const [categoryName, setCategoryName] = useState(undefined)
    const [banner, setBanner] = useState([])
    const [bannerName, setBannerName] = useState(undefined)

    const onFinish = (values) => {
        console.log(values.swiper)
        var reg = /^http|https/
        if (values.swiper.some(item => item.response === undefined && !reg.test(item.thumbUrl))) {
            message.warn('请等待图片上传结束')
            return
        }
        if (props.edit) {
            console.log('编辑模式')
            console.log('Success:', props.proid, values)
            values.swiper = values.swiper.map(item => {
                if (item.response) {
                    console.log(item.response)
                    return item.response.data.fileList.map(file => file.path)[0]
                } else {
                    return item.thumbUrl
                }
            })
            requestModifyShopList(props.proid, values).then(res => {
                console.log(res)
                message.success('修改商品成功')
                props.cb(values, fromRef)
            }).catch(err => {
                console.log(err)
                props.cb(values, fromRef)
            })
        } else {
            values.swiper = values.swiper.map(item => (item.response && item.response.data && item.response.data.fileList.map(file => file.path)[0]) || item.thumbUrl)
            // requestAddShopList(values).then(res => {
            //     console.warn(res)
            //     fromRef.current.resetFields()
            //     message.success(res.msg)
            // })
            props.cb(values, fromRef)
        }
    }

    const renderCategoryList = event => {
        requestCategoryList().then(res => {
            // console.log(res)
            setCategorys(res.data)
        })
    }

    const renderBannerList = event => {
        requestBrandlist().then(res => {
            // console.log(res)
            setBanner(res.data)
        })
    }

    const renderInit = (init) => {
        setTimeout(() => {
            fromRef.current.setFieldsValue(init)
        }, 30)
    }

    useEffect(() => {
        if (props.edit) {
            renderInit(props.initData)
        }else{
            fromRef.current.resetFields()
        }
        renderCategoryList()
        renderBannerList()
    }, [props.edit, props.initData])

    const onCategoryNameChange = event => {
        setCategoryName(event.target.value)
    }

    const addCategoryItem = e => {
        e.preventDefault()
        if (!categoryName) {
            message.warn('请输入添加的分类')
            return
        }
        if (categorys.includes(categoryName)) {
            message.warn('已经存在' + categoryName + '分类')
            setCategoryName(undefined)
            return
        }
        setCategorys([...categorys, categoryName])
        setCategoryName(undefined)
        requestAddCategoryList(categoryName).then(res => {
            console.log(res)
        })
    }

    const onBannerNameChange = event => {
        setBannerName(event.target.value)
    }

    const addBannerItem = e => {
        e.preventDefault()
        if (!bannerName) {
            message.warn('请输入添加的品牌')
            return
        }
        if (banner.includes(bannerName)) {
            message.warn('已经存在' + bannerName + '品牌')
            setBannerName(undefined)
            return
        }
        setBanner([...banner, bannerName])
        setBannerName(undefined)
        requestAddBrandList(bannerName).then(res => {
            console.log(res)
        })
    }

    const handlePreview = (file) => {
        let response = file.response
        if (!response && !props.edit) {
            message.info('文件还没有上传好')
        } else {
            // console.log(file.thumbUrl)
            // eslint-disable-next-line
            var reg = /.*[\/\\]/
            setPreviewImg((response && response.data && response.data.fileList[0]) || {
                path: file.thumbUrl,
                filename: file.thumbUrl.replace(reg, '')
            })
            setPreviewVisible(true)
        }
    }

    const handleCancel = () => {
        setPreviewVisible(false)
    }

    const handleRemove = (file) => {
        if (!props.edit) {
            removeUnusedPicture((file.response && file.response.data.fileList[0].path) || file.thumbUrl).then(res => {
                console.log(res)
            })
        } else {
            console.log('edit', file)
            message.success('成功移除商品图片')
            removeUnusedPicture((file.response && file.response.data.fileList[0].path) || file.thumbUrl).then(res => {
                console.log(res)
            })
            removeUnusedOnlinePicture({
                proid: props.proid,
                img: (file.response && file.response.data.fileList[0].path) || file.thumbUrl
            }).then(res => {
                console.log(res)
                props.cb(undefined, fromRef)
            })
        }
    }
    const element = <div className="addShop" style={{ height: '100%', overflow: 'auto' }}>
        <Form
            ref={fromRef}
            labelCol={{
                width: 600
            }}
            wrapperCol={{
                span: 10,
            }}
            layout="horizontal"
            initialValues={{
                size: 'large',
            }}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item label="商品名称" name="proname" rules={[{ required: true, message: '请输入商品名称' }]}>
                <Input disabled={props.proname}/>
            </Form.Item>
            <Form.Item label="商品介绍" name="desc" rules={[{ required: true, message: '请输入商品介绍' }]}>
                <Input/>
            </Form.Item>
            <Form.Item label="商品分类" name="category" rules={[{ required: true, message: '请输入商品分类' }]}>
                <Select
                    style={{ width: 300 }}
                    dropdownRender={menu => (
                        <>
                            {menu}
                            <Divider style={{ margin: '8px 0' }}/>
                            <Space align="center" style={{ padding: '0 8px 4px' }}>
                                <Input placeholder="请输入添加的分类" value={categoryName}
                                       onChange={onCategoryNameChange}/>
                                <Typography.Link onClick={addCategoryItem} style={{ whiteSpace: 'nowrap' }}>
                                    <PlusOutlined/> 添加
                                </Typography.Link>
                            </Space>
                        </>
                    )}
                >
                    {categorys.map(item => (
                        <Option key={item} value={item}>{item}</Option>
                    ))}
                </Select>
            </Form.Item>
            <Form.Item label="品牌名称" name="brand" rules={[{ required: true, message: '请输入品牌名称' }]}>
                <Select
                    style={{ width: 300 }}
                    dropdownRender={menu => (
                        <>
                            {menu}
                            <Divider style={{ margin: '8px 0' }}/>
                            <Space align="center" style={{ padding: '0 8px 4px' }}>
                                <Input placeholder="请输入添加的品牌" value={bannerName}
                                       onChange={onBannerNameChange}/>
                                <Typography.Link onClick={addBannerItem} style={{ whiteSpace: 'nowrap' }}>
                                    <PlusOutlined/> 添加
                                </Typography.Link>
                            </Space>
                        </>
                    )}
                >
                    {banner.map(item => (
                        <Option key={item} value={item}>{item}</Option>
                    ))}
                </Select>
            </Form.Item>
            <Form.Item label="商品原价" name="originprice" rules={[{ required: true, message: '请输入商品原价' }]}>
                <InputNumber min={0}/>
            </Form.Item>
            <Form.Item label="商品折扣" name="discount" rules={[{ required: true, message: '请输入商品折扣' }]}>
                <InputNumber max={10} min={0}/>
            </Form.Item>
            <Form.Item label="商品库存" name="stock" rules={[{ required: true, message: '请输入商品库存' }]}>
                <InputNumber min={0}/>
            </Form.Item>
            <Form.Item
                name="swiper"
                label="商品图片"
                valuePropName="fileList"
                getValueFromEvent={normFile}
                rules={[{ required: true, message: '需上传商品图片' }]}
            >
                <Upload onPreview={handlePreview} onRemove={handleRemove} name="logo" maxCount={4}
                        action={baseUrl + '/up/upload'}
                        listType="picture" multiple={true}>
                    <Button icon={<UploadOutlined/>}>Click to upload</Button>
                </Upload>
            </Form.Item>
            <Form.Item label="">
                <Button type="primary" htmlType="submit">
                    {props.edit ? '修改商品' : '添加商品'}
                </Button>
            </Form.Item>
        </Form>
        <Modal visible={previewVisible} title={previewImg.filename} footer={null} onCancel={handleCancel}>
            <img alt="加载失败" src={previewImg.path} width="100%"/>
        </Modal>
    </div>

    return (
        element
    )
}

export default connect((state) => {
    return {
        show: state.getIn(['fade', 'show'])
    }
})(AddShop)
